//
//  DHAddressViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/16.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHAddressViewController.h"
#import "DHAddressTableViewCell.h"

@interface DHAddressViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, AMapSearchDelegate, AMapLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;
@property (weak, nonatomic) IBOutlet UIButton *searchBGButton;
@property (weak, nonatomic) IBOutlet UILabel *noLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSafeAreaLayout;

@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) NSString *currentCitycode;

@property (strong, nonatomic) AMapSearchAPI *search;
@property (strong, nonatomic) AMapLocationManager *locationManager;

@property (strong, nonatomic) CLLocation *currentLocation;

@end

@implementation DHAddressViewController

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (NSArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([UIDevice systemVersion] < 11) {
        self.topSafeAreaLayout.constant = 20;
    }
    self.titleLabel.text = @"地址选择";
    self.view.backgroundColor = RGB(244, 244, 244);
    self.searchView.layer.cornerRadius = 5.5;
    self.searchView.layer.masksToBounds = YES;
    
    self.searchBGButton.hidden = YES;
    self.searchBGButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    [self.searchBGButton bk_addEventHandler:^(id sender) {
        self.searchBGButton.hidden = YES;
        [self.view endEditing:YES];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHAddressTableViewCell" bundle:nil] forCellReuseIdentifier:kDHAddressTableViewCell];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [self initLocationManager];
}

// 定位
- (void)initLocationManager
{
    if (self.locationManager == nil){
        
        self.locationManager = [[AMapLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        //   定位超时时间，最低2s，此处设置为2s
        self.locationManager.locationTimeout =2;
        //   逆地理请求超时时间，最低2s，此处设置为2s
        self.locationManager.reGeocodeTimeout = 2;
        
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            if (error){
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                if (error.code == AMapLocationErrorLocateFailed){
                    return;
                }
            }
            
            NSLog(@"location:%@", location);
            //            [self.mapView setCenterCoordinate:location.coordinate];
            //            self.startPoint = [AMapNaviPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            
            if (regeocode){
                NSLog(@"reGeocode:%@", regeocode);
                self.currentCitycode = regeocode.citycode;
            }
            if (location) {
                self.currentLocation = location;
            }
        }];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.searchBGButton.hidden = NO;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.searchBGButton.hidden = YES;
    [self.searchTF resignFirstResponder];
    [self startSearchWithKey:textField.text];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    [self startSearchWithKey:textField.text];
    return YES;
}

- (void)startSearchWithKey:(NSString *)keyString{
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords            = keyString;
//    request.city                = @"";
    request.types               = @"";
    request.requireExtension    = YES;
    
    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
    request.cityLimit           = NO;
    request.requireSubPOIs      = YES;
    [self.search AMapPOIKeywordsSearch:request];
}

#pragma mark - AMapSearchDelegate
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    self.noLabel.hidden = YES;
    if (response.pois.count == 0){
//        [NSObject showHudTipStr:@"未找到相关位置"];
        return;
    }else{
        self.dataArray = response.pois;
        [self.tableView reloadData];
    }
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    if (error) {
        [NSObject showHudTipStr:@"搜索失败"];
    }
}

#pragma mark - UITableViewDelegate and UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DHAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHAddressTableViewCell forIndexPath:indexPath];
    AMapPOI *poi = [self.dataArray objectAtIndex:indexPath.row];
    [cell updateCell:poi andCurrentLocation:self.currentLocation];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AMapPOI *poi = [self.dataArray objectAtIndex:indexPath.row];
    NSString *address = [NSString stringWithFormat:@"%@%@%@",poi.province,poi.city,poi.district];
    NSString *detailAddress = [NSString stringWithFormat:@"%@",poi.address];
    GeoCode *geoCode = [[GeoCode alloc] init];
    geoCode.province = poi.province;
    geoCode.city = poi.city;
    geoCode.district = poi.district;
    geoCode.address = poi.address;
    Location *location = [[Location alloc] init];
    [location.coordinates addObject:@(poi.location.longitude)];
    [location.coordinates addObject:@(poi.location.latitude)];
    if (self.isHomePush) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"home_gaodeaddressselected" object:@{@"address":address,@"detailAddress":detailAddress,@"geoCode":geoCode,@"location":location}];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"gaodeaddressselected" object:@{@"address":address,@"detailAddress":detailAddress,@"geoCode":geoCode,@"location":location}];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
